package com.supplychain.financial.parent.common.util;

import org.apache.commons.lang.time.DateFormatUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 日期相关工具
 */
public class DateUtil {
    /**
     * 通过年周获取该周所在的星期四，星期四肯定是在所属年周的年中
     * @return
     */
    public static Date  getThursdayByYearWeek(Integer year,Integer week) {

        //实例化工具
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setMinimalDaysInFirstWeek(4);

        //某年的第一周周一最早是上一年的12-29
        //设置条件年的第一周最早周一
        calendar.set(year-1,11,29);

        //条件周的最早周一
        calendar.add(Calendar.DATE, (week-1)*7);

        Date date = null;

        //加一个循环次数判断，如果循环大于7次还没有得到结果，那么数据就是错的，直接返回。
        int times = 0;
        while (true) {
            if (times==7) {
                break;
            }
            times++;
            int week1 = calendar.get(Calendar.WEEK_OF_YEAR);
            //不断增加时间去找正确的周一
            //判断依据是：week1比week小，或者，week是一而week1不是
            if (week1<week || (week==1 && week1 != 1)) {
                calendar.add(Calendar.DATE, 1);
                continue;
            }
            calendar.add(Calendar.DATE, 3);
            date = calendar.getTime();
            break;
        }
        return date;
    }

    public static List<Map<String, String>> getYearWeekByYearMonth(Integer year, Integer month) {

        //实例化工具
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setMinimalDaysInFirstWeek(4);


        List<Map<String, String>> result = new ArrayList<>();

        for (int i = 1 ;i <= 53 ; i++) {
            Date date = DateUtil.getThursdayByYearWeek(year,i);
            if (date == null) {
                continue;
            }
            calendar.setTime(date);

            if (calendar.get(Calendar.YEAR) == year && calendar.get(Calendar.MONTH) ==  month-1) {
                Map<String,String> data = new HashMap<>();
                data.put("data" , String.valueOf(i));
                data.put("value" , String.valueOf(i));
                result.add(data);

            }
        }

        return result;

    }
    
    
    private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", 
    		"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" };

    	/**
    	 * 得到当前日期字符串 格式（yyyy-MM-dd）
    	 */
    	public static String getDate() {
    		return getDate("yyyy-MM-dd");
    	}
    	
    	/**
    	 * 得到当前日期字符串 格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
    	 */
    	public static String getDate(String pattern) {
    		return DateFormatUtils.format(new Date(), pattern);
    	}
    	
    	/**
    	 * 得到日期字符串 默认格式（yyyy-MM-dd） pattern可以为："yyyy-MM-dd" "HH:mm:ss" "E"
    	 */
    	public static String formatDate(Date date, Object... pattern) {
    		String formatDate = null;
    		if (pattern != null && pattern.length > 0) {
    			formatDate = DateFormatUtils.format(date, pattern[0].toString());
    		} else {
    			formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
    		}
    		return formatDate;
    	}

    	/**
    	 * 得到当前时间字符串 格式（HH:mm:ss）
    	 */
    	public static String getTime() {
    		return formatDate(new Date(), "HH:mm:ss");
    	}

    	/**
    	 * 得到当前日期和时间字符串 格式（yyyy-MM-dd HH:mm:ss）
    	 */
    	public static String getDateTime() {
    		return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    	}

    	/**
    	 * 得到当前年份字符串 格式（yyyy）
    	 */
    	public static String getYear() {
    		return formatDate(new Date(), "yyyy");
    	}

    	/**
    	 * 得到当前月份字符串 格式（MM）
    	 */
    	public static String getMonth() {
    		return formatDate(new Date(), "MM");
    	}

    	/**
    	 * 得到当天字符串 格式（dd）
    	 */
    	public static String getDay() {
    		return formatDate(new Date(), "dd");
    	}

    	/**
    	 * 得到当前星期字符串 格式（E）星期几
    	 */
    	public static String getWeek() {
    		return formatDate(new Date(), "E");
    	}
    	

    	/**
    	 * 获取过去的天数
    	 * @param date
    	 * @return
    	 */
    	public static long pastDays(Date date) {
    		long t = new Date().getTime()-date.getTime();
    		return t/(24*60*60*1000);
    	}
    	
    	/**
    	 * 根据传入的时间，获取几个月之后或之前的时间
    	 * @param date
    	 * @param months
    	 * @return
    	 */
    	public static Date monthOperator(Date date,int months){
    		Calendar cal = Calendar.getInstance();
    		cal.setTime(date);
    		cal.add(Calendar.MONTH, months);
    		Date endDate = cal.getTime();
    		return endDate;
    	}
    	
    	 /**  
         * 计算两个日期之间相差的天数  zc
         * @param smdate 较小的时间 
         * @param bdate  较大的时间 
         * @return 相差天数 
         * @throws ParseException  
         */    
        public static int daysBetween(Date smdate,Date bdate)    
        {    
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
            try {
    			smdate=sdf.parse(sdf.format(smdate));
    			 bdate=sdf.parse(sdf.format(bdate));  
    			
    		} catch (ParseException e) {
    			e.printStackTrace();
    			return -1;
    		}  
            Calendar cal = Calendar.getInstance();    
            cal.setTime(smdate);    
            long time1 = cal.getTimeInMillis();                 
            cal.setTime(bdate);    
            long time2 = cal.getTimeInMillis();         
            long between_days=(time2-time1)/(1000*3600*24);  
                
           return Integer.parseInt(String.valueOf(between_days));           
        }  
        
        /**
    	 * 获取当前时间所在的星期的星期一和星期日的日期 zc
    	 * @return 
    	 */
    	public static Map<String,String> getWeekBeginAndEndTime() {
    		Map<String,String> result = new HashMap<>();
    		Calendar cal = Calendar.getInstance();
    		cal.setTime(new Date());
    		int d = 0;
    		if(cal.get(Calendar.DAY_OF_WEEK)==1){
    			d = -6;
    		}else{
    			d = 2-cal.get(Calendar.DAY_OF_WEEK);
    		}
    		cal.add(Calendar.DAY_OF_WEEK, d);
    		//所在周开始日期
    		System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
    		result.put("beginTime", new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
    		cal.add(Calendar.DAY_OF_WEEK, 6);
    		//所在周结束日期
    		System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
    		result.put("endTime", new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()));
    		return result;

    	}
    	
    	public static String getYearWeek(String date){
    		if(StringUtils.isNullOrEmpty(date)){
    			Date now = new Date();
    			Calendar calendar = Calendar.getInstance();
    			calendar.setFirstDayOfWeek(Calendar.MONDAY);
    			calendar.setTime(now);
    			int week = calendar.get(Calendar.WEEK_OF_YEAR);
    			calendar.add(Calendar.DAY_OF_MONTH, -7);
    			int year = calendar.get(Calendar.YEAR);  
    			if(week<calendar.get(Calendar.WEEK_OF_YEAR)){  
    			    year+=1;  
    			}  
    			String year_week = year+"-"+week;
    			return year_week;
    		}
    		return null;
    	}
}
